import datetime
import random

from rest_framework import status
from rest_framework.generics import GenericAPIView, ListCreateAPIView, CreateAPIView
from rest_framework.response import Response
from rest_framework.views import APIView

from Admin.adminSerializers import UserSerializer
from Admin.models import  Article_comment, Articles,Questions,\
    User
from Web1.models import Book_recommend, Book_category, Feedback, Movie, Wish
from Admin.utils import token_confirm
from Web1.serializers import RecommendArticleSerializer, UserLoginSerializer, LatestQuestionsSerializer, \
    ArticleCommentsSerializer, QuestionAnswerSerializer, RegisterSerializer, RecommendBookSerializer, \
    BookCategorySerializer, FeedbackSerializer, MoviesSerializer,WishSerializer


#用户注册
class Web1RegisterView(CreateAPIView):
    queryset = User.objects.all()
    serializer_class = RegisterSerializer

    def create(self,request, *args, **kwargs):
        serializer = self.get_serializer(data=request.data)   #反向序列化
        if serializer.is_valid():
            print("验证通过")
            registerData = serializer.data
            register_date = datetime.datetime.now()
            avatar = "https://wyy-data.oss-cn-beijing.aliyuncs.com/avatar/IMG_5570(20211023-124640).JPG"
            #这里有问题
            uid = random.randint(100,20000)
            #创建一个新用户存入数据库当中
            res = User.objects.create(**registerData, registration_data=register_date, avatar=avatar, uid=uid)

            if res:
                print("注册成功")
                return Response({
                    'code': status.HTTP_200_OK,
                    'msg': '注册成功',
                })
            else:
                print("无法创建用户")
                return Response({
                    'code': status.HTTP_404_NOT_FOUND,
                    'msg': "无法创建用户",
            })

        else:
            print("验证失败")
            return Response({
                'code': status.HTTP_404_NOT_FOUND,
                'msg': "校验参数错误",
                'errors': serializer.errors
            })

#用户登录
class Web1UserLoginView(CreateAPIView):
    queryset = User.objects.all()
    serializer_class = UserLoginSerializer

    def create(self, request, *args, **kwargs):
        serializer = self.get_serializer(data=request.data)
        if serializer.is_valid():
            print("验证成功")
            #1.生成token
            account = serializer.data.get('phone')  #获取到账号
            user = User.objects.filter(phone=account).first() #获取到该用户
            # print(user)
            uid = user.uid  #获取该用户的id号
            token = token_confirm.generate_validate_token(uid=uid)
            user_serializer = UserSerializer(instance=user)

            #2.返回数据
            return Response({
                'code':status.HTTP_200_OK,
                'msg':'登录成功',
                'data':{
                    'authToken': token,
                    'userInfo': user_serializer.data
                }
            })
        else:
            #验证失败了
            print("验证失败")
            return Response({
                'code':status.HTTP_404_NOT_FOUND,
                'msg':"校验参数错误",
                'errors':serializer.errors,
                'authToken':None
            })

# 用户信息的更新
# class Web1UpdateUserInfo(CreateAPIView):
#     queryset = User.objects.all()
#     serializer_class = UserSerializer
#
#     def create(self, request, *args, **kwargs,):
#         serializer = self.get_serializer(data=request.data);
#         if serializer.is_valid():
#             print("验证通过")
#             # print(serializer.data)
#             updateUser = serializer.data
#             print(updateUser)
#             uid = updateUser.uid
#             print('uid', uid)
#             # currentUser = User.objects.get(pk=1)
#             # print('current',currentUser)
#             # User.objects.update(serializer.data)
#
#             return Response({
#                 'code':200,
#                 'msg' :'信息修改成功'
#             })
#         else:
#             return Response({
#                 'code':404,
#                 'msg' :'信息修改出错',
#                 'err' :serializer.errors
#             })
#更新用户的相关信息
class Web1UpdateUserInfo(GenericAPIView):
    queryset = User.objects.all()
    serializer_class = UserSerializer

    def get(self,request,pk):
        #print('get请求')
        user = User.objects.filter(uid=pk).first()
        #print(22222)
        serializer = self.get_serializer(user)
        #print(serializer.data)

        return Response({
            'code':200,
            'msg':'ok',
            'data': {
                'userInfo':serializer.data
            }
        })

    def post(self, request,pk):

        user = User.objects.filter(uid=pk)
        serializer = self.get_serializer(data=request.data)
        if serializer.is_valid():
            update_info = serializer.data
            user.update(username= update_info['username'], description = update_info['description'], \
                        personality=update_info['personality'],email = update_info['email'])

            print('更新成功')

            return Response({
                'code':200,
                'msg':'信息修改成功'
            })
        else:
            return Response({
                'code':404,
                'msg' :'信息修改出错',
                'err' :serializer.errors
            })


#返回该用户的关注信息
class Web1FollowView(APIView):
    def get(self,request):

        return Response(
            {
                'code':200,
                'msg': 'ok',
                'data': "follows"
            }
        )

#返回推荐文章的信息
class Web1RecommendView(ListCreateAPIView):
    queryset = Articles.objects.all()
    serializer_class = RecommendArticleSerializer
    def list(self,request, *args, **kwargs):
        queryset = self.get_queryset()
        serializer = self.get_serializer(queryset, many=True)
        return Response(
            {
                'code':200,
                'msg':'ok',
                'data':serializer.data
            }
        )

#返回一条文章的信息,以及相关的评论
class Web1ArticleView(GenericAPIView):
    queryset = Articles.objects.all()
    serializer_class = RecommendArticleSerializer

    def get(self, request,pk):
        article = self.get_object()
        serializer = self.get_serializer(article)
        comments = article.a_comments.all()
        # print(comments)
        serializer2 = ArticleCommentsSerializer(instance=comments, many=True)
        # print(serializer2.data)

        return Response({
            'code':status.HTTP_200_OK,
            'msg':'ok',
            'data':
                {
                    'article':serializer.data,
                    'article_comments':serializer2.data
                 }
        })

#返回最新问题的信息
class Web1QuestionView(ListCreateAPIView):
    queryset = Questions.objects.all()
    serializer_class = LatestQuestionsSerializer
    def list(self,request,*args, **kwargs):
        queryset = self.get_queryset()
        serializer = self.get_serializer(queryset, many=True)
        return Response(
            {
                'code':200,
                'msg':'ok',
                'data':serializer.data
            }
        )

#返回一条问题的信息,以及相关问题的回复,以及每条回复的评论信息
class Web1QuestionByIDView(GenericAPIView):
    queryset = Questions.objects.all()
    serializer_class = LatestQuestionsSerializer
    def get(self, request, pk):
        question = self.get_object()
        serializer = self.get_serializer(question)
        question_answers = question.q_answers.all()
        serializer2 = QuestionAnswerSerializer(instance=question_answers,many=True)
        #一条回答的相关评论怎么搞进去
        #每个回答的评论，就是answerComments， 根据回答的id号查询出来然后加到回答的属性里面去
        # answer_comments_object =
        # answer_comments = QuestionAnswerCommentSerializer(answer_comments_object, many=True).data

        return Response(
            {
                'code':200,
                'msg':'ok',
                'data':
                    {
                        'question':serializer.data,
                        'question_answers':serializer2.data
                    }
            }
        )

#返回讨论组信息
class Web1DisGroupView(APIView):
    def get(self,request):
        return Response(
            {
                'code':200,
                'data':"groups"
            }
        )


#添加文章的评论
class Web1AddArticleCommentsView(CreateAPIView):
    queryset = Article_comment.objects.all()
    serializer_class = ArticleCommentsSerializer

    def create(self, request, *args, **kwargs):
        Response({
            'code':200,
            'msg':'ok',
            'data':'add_article_comment'
        })

#添加问题的回答
class Web1AddQuestionAnswerView(CreateAPIView):

    def create(self, request, *args, **kwargs):
        Response({
            'code': 200,
            'msg': 'ok',
            'data': 'add_question_answer'
        })

class Web1FollowsByUid(GenericAPIView):
    queryset = User.objects.all()
    serializer_class = UserSerializer

    def get(self, request, pk):  #
        return Response({
            'code':status.HTTP_200_OK,
            'msg': 'ok'
        })



#返回uid为pk的用户的所有文章
class Web1ArticlesByUid(GenericAPIView):
    queryset = Articles.objects.all()
    serializer_class = RecommendArticleSerializer

    def get(self, request, pk):
        articles = Articles.objects.filter(article_author_id=pk)
        serializer = self.get_serializer(articles,many=True)
        # print(articles)
        # print(serializer.data)

        return Response({
            'code':200,
            'msg':'ok',
            'data':serializer.data
        })

class Web1BookCategoryView(GenericAPIView):
    queryset = Book_category.objects.all()
    serializer_class = BookCategorySerializer

    def get(self, *args, **kwargs):
        queryset = self.get_queryset()
        serializer = self.get_serializer(queryset, many=True)
        # print(serializer.data)

        return Response(
            {
                'code': 200,
                'msg': 'ok',
                'data': serializer.data
            }
        )

# 获取书籍推荐的相关信息
class Web1RecommendBooksView(GenericAPIView):
    queryset = Book_recommend.objects.all()
    serializer_class = RecommendBookSerializer

    def get(self, *args, **kwargs):
        queryset = self.get_queryset()
        serializer = self.get_serializer(queryset, many=True)
        # print(serializer.data[:20])

        return Response(
            {
                'code': 200,
                'msg': 'ok',
                'data': serializer.data
            }
        )

#电影推荐
class Web1GetMoviesView(GenericAPIView):
    queryset = Movie.objects.all()
    serializer_class = MoviesSerializer
    def get(self,*args, **kwargs):
        queryset = self.get_queryset()
        serializer = self.get_serializer(queryset, many=True)
        return Response(
            {
                'code':200,
                'msg':'ok',
                'data': serializer.data[:30]
            }
        )


# 接收反馈信息
class Web1GetFeedbackView(GenericAPIView):
    queryset = Feedback.objects.all()
    serializer_class = FeedbackSerializer

    def post(self, request):
        serializer = self.get_serializer(data=request.data)
        if serializer.is_valid():
            opinion_content = serializer.data

            opinion = Feedback(opinion_id=None,opinion_content=opinion_content,publish_date=datetime.datetime.now())
            opinion.save()
            return Response({
                'code': 200,
                'msg': '反馈信息已经接收'
            })

        else:
            # print(serializer.errors)
            return Response({
                'code':404,
                'msg':'反馈信息出错',
                'err':serializer.errors
            })

# wishes相关接口
class Web1GetWishesView(GenericAPIView):
    queryset = Wish.objects.all()
    serializer_class = WishSerializer

    def get(self, *args, **kwargs):
        queryset = self.get_queryset()
        serializer = self.get_serializer(queryset, many=True)
        # print(serializer.data)

        return Response({
            'code':200,
            'msg':'ok',
            'data': serializer.data
        })

class Web1PushWishesView(GenericAPIView):
    queryset = Wish.objects.all()
    serializer_class = WishSerializer

    def post(self, request):
        serializer = self.get_serializer(data=request.data)
        if serializer.is_valid():
            # 数据存入数据库中
            wish = serializer.data
            print(wish)
            wishItem = Wish(wish_id=None, wish_content=wish['wish_content'],uid=wish['uid'])
            wishItem.save()
            return Response({
                'code': 200,
                'msg': 'ok',
            })
        else:
            return Response({
                'code': 404,
                'msg': '反馈信息出错',
                'err': serializer.errors
            })

